#include "defs.h"


LOG_LEVEL g_loglevel = TRACE;
static FILE* s_fp = stderr;
static const char* maplevel[] = {
			"TRACE",
			"NOTICE",
			"DEBUG",
			"WARNING",
			"FATAL"
			};

static const char* level2str(LOG_LEVEL level) {
	if (level > 4 || level < 0)
		return "Unknown";
	else
		return maplevel[level];
} 
void _trace(LOG_LEVEL loglevel,const char *fmt, ...) {
	if (loglevel < g_loglevel)
		return;
	static Mutex mutex;
	va_list ap;
	if (s_fp) {
		mutex.lock();
		fprintf(s_fp, "[%s]", level2str(loglevel));
		if (loglevel >= DEBUG) {
			struct timeval timeofday;
			gettimeofday(&timeofday, NULL);
			time_t now = timeofday.tv_sec;
			struct tm newtime;
			struct tm *date = localtime_r(&now, &newtime);
		
			fprintf(s_fp, "[%02d-%02d %02d:%02d:%02d] ",
					date->tm_mon + 1,
					date->tm_mday,
					date->tm_hour,
					date->tm_min,
					date->tm_sec);
		}
		va_start(ap, fmt);
		vfprintf(s_fp, fmt, ap);
		mutex.unlock();
		fflush(s_fp);
	}
}

void set_log_file(FILE* fp) {
	s_fp = fp;
}
